<template>
  <div class="app-container">
    <div class="page-top app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="城市标签" prop="cityName">
          <el-select
            v-model="queryParams.cityName"
            @change="handleQuery"
            fit-input-width
            placeholder="请选择"
          >
            <el-option
              v-for="item in cityNameOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区域名称" prop="areaId">
          <ApiSelect
            v-model="queryParams.areaId"
            :api="selectState.areaList.api"
            :params="{ pageNum: 1, pageSize: 999999, cityName: queryParams.cityName }"
            :resultField="selectState.areaList.resultField"
            :valueField="selectState.areaList.valueField"
            :labelField="selectState.areaList.labelField"
            :immediate="true"
          />
        </el-form-item>
        <el-form-item label="线路名称" prop="routeId">
          <ApiSelect
            class="form-input"
            v-model="queryParams.routeId"
            :api="selectState.route.api"
            :params="{ areaId: queryParams.areaId }"
            :valueField="selectState.route.valueField"
            :labelField="selectState.route.labelField"
            :immediate="false"
          />
        </el-form-item>
        <el-form-item label="点位名称" prop="positionId">
          <ApiSelect
            class="form-input"
            v-model="queryParams.positionId"
            :api="selectState.point.api"
            :params="{ routeId: queryParams.routeId }"
            :valueField="selectState.point.valueField"
            :labelField="selectState.point.labelField"
            :immediate="false"
          />
        </el-form-item>
        <el-form-item label="">
          <div class="btn-group">
            <el-button plain v-hasPermi="['org:user:export']" @click="handleExport">
              导出数据
            </el-button>

            <el-radio-group v-model="radioValue" @change="handleDateRange" style="flex-shrink: 0">
              <el-radio-button label="当天" />
              <el-radio-button label="最近7天" />
              <el-radio-button label="最近30天" />
            </el-radio-group>

            <el-date-picker
              v-model="state.timeRange"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="dateChange"
              :clearable="false"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </div>
        </el-form-item>
        <el-form-item label="设备名称" prop="machineName">
          <el-input
            style="width: 200px"
            maxlength="16"
            v-model.trim="queryParams.machineName"
            placeholder="请输入套设备名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="total">
      <div class="header">数据总览</div>
      <div class="cards">
        <div class="card" v-for="item in totalData" :key="item.lable">
          <div class="label">{{ item.lable }}</div>
          <div class="value">{{ totalValue[item.value] }}</div>
        </div>
      </div>
    </div>
    <div style="padding: 0 20px">
      <div class="header">数据明细列表</div>
      <el-table v-loading="state.loading" :data="tableList" style="width: 100%">
        <el-table-column
          label="点位名称"
          show-overflow-tooltip
          align="center"
          prop="positionName"
        />
        <el-table-column label="设备" align="center" prop="machineNum">
          <template #default="{ row }">
            <div>
              <el-link
                :underline="false"
                type="primary"
                :disabled="!hasPermi(['org:user:detail'])"
                @click="handleDetail(row)"
                >{{ row.machineNum }}</el-link
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column label="累计用户数" align="center" prop="totalUser">
          <template #default="{ row }">
            <div>
              <el-link
                :underline="false"
                type="primary"
                :disabled="!hasPermi(['org:user:total'])"
                @click="handleUser(row, '累计用户数')"
                >{{ row.totalUser }}</el-link
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column label="下单用户数" align="center" prop="orderUser">
          <template #default="{ row }">
            <div>
              <el-link
                :underline="false"
                type="primary"
                :disabled="!hasPermi(['org:user:order'])"
                @click="handleUser(row, '下单用户数')"
                >{{ row.orderUser }}</el-link
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column label="新用户数" align="center" prop="newUser">
          <template #default="{ row }">
            <div>
              <el-link
                :underline="false"
                type="primary"
                :disabled="!hasPermi(['org:user:new'])"
                @click="handleUser(row, '新用户数')"
                >{{ row.newUser }}</el-link
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column label="新用户环比" align="center" prop="newUserSequentialGrowth">
          <template #default="{ row }"> {{ row.newUserSequentialGrowth || '0.00' }}% </template>
        </el-table-column>
        <el-table-column label="新用户占比" align="center" prop="newUserRatio">
          <template #default="{ row }"> {{ row.newUserRatio || '0.00' }}% </template>
        </el-table-column>
        <el-table-column label="复购率" align="center" prop="repurchaseRate">
          <template #default="{ row }"> {{ row.repurchaseRate || '0.00' }}% </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="state.total > 0"
        :total="state.total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <detailList ref="detailListRef"></detailList>
    <userList ref="userListRef"></userList>
  </div>
</template>

<script setup name="DeviceAnalysis">
import { parseTime } from '@/utils/tools'
import { onMountedOrActivated } from '@/hooks/common'
import useGlobalStore from '@/store/modules/global'
import { useOrganApiConfig } from '@/hooks/service'
import detailList from './components/detailList.vue'
import userList from './components/userList.vue'
import { hasPermi } from '@/utils/tools'
import { getUserLayerListApi, getUserLayerTotalApi } from '@/api/statistic'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)
const { proxy } = getCurrentInstance()
const selectState = useOrganApiConfig()
const radioValue = ref('当天')
const tableList = ref([])
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  cityName: cityNameOptions.value[0],
  areaId: '',
  routeId: '',
  positionId: '',
  machineName: ''
})
const totalData = [
  { lable: '累计用户数', value: 'totalUser' },
  { lable: '下单用户数', value: 'orderUser' },
  { lable: '新用户数', value: 'newUser' }
]
const totalValue = ref({
  totalUser: 0,
  orderUser: 0,
  newUser: 0
})
const state = reactive({
  total: 0,
  loading: false,
  timeRange: [
    parseTime(new Date(), '{y}-{m}-{d}') + ' 00:00:00',
    parseTime(new Date(), '{y}-{m}-{d}') + ' 23:59:59'
  ]
})

const queryRef = ref(null)
// 重置
function resetQuery() {
  queryRef.value.resetFields()
  radioValue.value = '当天'
  handleDateRange('当天')
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

const dateChange = () => {
  radioValue.value = ''
  handleQuery()
}
function handleDateRange(val) {
  const end = parseTime(new Date(), '{y}-{m}-{d}') + ' 23:59:59'
  const start = new Date()
  switch (val) {
    case '最近30天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
      state.timeRange = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    case '最近7天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
      state.timeRange = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    case '当天':
      state.timeRange = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    default:
      break
  }
  handleQuery()
}
async function getList() {
  state.loading = true
  const [startDate, endDate] = state.timeRange
  queryParams.value.startDate = startDate ? startDate : ''
  queryParams.value.endDate = endDate ? endDate : ''
  try {
    const r = await getUserLayerListApi(queryParams.value)
    tableList.value = r?.data?.rows || []
    state.total = r?.data?.total || 0
    const res = await getUserLayerTotalApi(queryParams.value)
    totalValue.value = res?.data || {}
  } finally {
    state.loading = false
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'operation/statistics/admin/user-layer/export',
    queryParams.value,
    `用户分层数据${new Date().getTime()}.xlsx`
  )
}

// 设备详情
const detailListRef = ref(null)
function handleDetail(row) {
  detailListRef.value.init(row, queryParams.value)
}
// 用户详情
const userListRef = ref(null)
function handleUser(row, name) {
  userListRef.value.init(row, name, queryParams.value)
}

/**init +  onActivated*/
onMountedOrActivated(getList)
</script>

<style lang="scss" scoped>
.app-container {
  min-width: 960px;
  overflow-x: auto;
}
.page-top {
  .btn-group {
    display: flex;
    align-items: center;
  }
  .el-radio-group {
    margin: 0 10px;
  }
  div {
    margin-right: 15px;
  }
}
.total {
  width: 960px;
  padding: 20px 0 0 20px;
  overflow-x: auto;
}
.cards {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  .card {
    width: 300px;
    height: 120px;
    text-align: left;
    display: flex;
    flex-direction: column;
    justify-content: center;
    border-radius: 6px;
    border: 1px solid #33333390;
    padding: 0 20px;
    margin-bottom: 20px;
    .value {
      font-size: 25px;
      font-weight: 500;
      margin-top: 10px;
    }
  }
}
.header {
  font-size: 20px;
  margin-bottom: 10px;
}
</style>
